/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.punishinform.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.ConvertUpMoneyUtil;
import com.icinfo.cloud.provider.punish.common.datareport.enums.CaseChangeOperationTypeEnum;
import com.icinfo.cloud.provider.punish.common.datareport.service.ICaseDataChangeReportRecordService;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.config.dto.CompareDiscretionDto;
import com.icinfo.cloud.provider.punish.config.dto.CompareSingleDiscretionDto;
import com.icinfo.cloud.provider.punish.config.enums.DecideBasisTypeEnum;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.IConfigOrgDecideBasisInfoService;
import com.icinfo.cloud.provider.punish.config.service.IConfigOrgRegulatoryDiscretionRuleHisService;
import com.icinfo.cloud.provider.punish.fastcase.service.IFastCaseDocumentRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.AppendixDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseReasonInfoAdjustDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandleTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartiesReasonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PunishKindsEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesRecordVo;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseEmergencyReasonInfoDto;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.PersonReasonIds;
import com.icinfo.cloud.provider.punish.ucase.criminaltransfer.mapper.CaseCriminalTransferFileMapper;
import com.icinfo.cloud.provider.punish.ucase.punishinform.dto.*;
import com.icinfo.cloud.provider.punish.ucase.punishinform.service.IInformInvestigationEndService;
import com.icinfo.cloud.provider.punish.ucase.punishinform.vo.InformInvestigationEndFormVo;
import com.icinfo.cloud.provider.punish.ucase.punishinform.vo.InvestEndMultiple;
import com.icinfo.cloud.provider.punish.ucase.punishinform.vo.PunishRuleInfo;
import com.icinfo.cloud.provider.punish.ucase.punishinform.vo.ViolateRuleInfo;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.DateUtils;
import com.icinfo.framework.tools.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 描述:  temp 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年02月13日
 */
@Service
public class InformInvestigationEndServiceImpl extends MyBatisServiceSupport implements IInformInvestigationEndService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(InformInvestigationEndServiceImpl.class);
    @Autowired
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;
    @Autowired
    private CaseMainInfoMapper caseMainInfoMapper;
    @Autowired
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;
    @Autowired
    private ICaseMainInfoService caseMainInfoService;
    @Autowired
    private ICaseMainDetailInfoService caseMainDetailInfoService;
    @Autowired
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Autowired
    private ICaseAppendixRecordService caseAppendixRecordService;
    @Autowired
    private CaseAppendixRecordMapper caseAppendixRecordMapper;
    @Autowired
    private CaseMainDetailAuxiliaryInfoMapper caseMainDetailAuxiliaryInfoMapper;
    @Resource
    private IConfigOrgDecideBasisInfoService configOrgDecideBasisInfoService;
    @Resource
    private ICaseInfoAdjustRecordService caseInfoAdjustRecordService;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private ICaseMainDetailAuxiliaryInfoService caseMainDetailAuxiliaryInfoService;
    @Resource
    private ICaseDataChangeReportRecordService caseDataChangeReportRecordService;
    @Resource
    private CaseCriminalTransferFileMapper caseCriminalTransferFileMapper;
    @Resource
    private IFastCaseDocumentRecordService fastCaseDocumentRecordService;
    @Resource
    private CaseTemporaryRecordMapper caseTemporaryRecordMapper;
    @Resource
    private IConfigOrgRegulatoryDiscretionRuleHisService configOrgRegulatoryDiscretionRuleHisService;


    /**
     * 获取调查终结表单数据
     *
     * @param request
     * @return {@link Result< InformInvestigationEndFormVo>}
     * @author liyafeng
     * @date 2022/2/25
     */
    @Override
    public Result<InformInvestigationEndFormVo> getInformInvestigationEndFormBaseinfo(InvestigationEndRequest request) {
        //查询案件主表
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(request.getCaseId());
        //查询案件详情表
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(request.getCaseId());
        //获取案件案由、当事人类型；1：单案由单当事人 2：多案由单当事人 3：单案由多当事人
        String casePartiesReasonType = caseMainInfo.getCasePartiesReasonType();
        //获取处置方式；0：常规处罚 1：合并处罚 2：分别处罚
        String handleType = caseMainInfo.getHandleType();
        //List<InvestEndMultiple> investEndMultiple=new ArrayList<>();
        InformInvestigationEndFormVo informInvestigationEndFormVo = formInformInvestigationEndFormVo(request.getCaseId(), request.getDocumentCatalogCode(), casePartiesReasonType, handleType, caseMainInfo, caseMainDetailInfo);

        /*InformInvestigationEndFormVo informInvestigationEndFormVo=new InformInvestigationEndFormVo();
        //获取案由、违则、罚则数据
        Example example=new Example(CaseReasonMainRecord.class);
        example.createCriteria().andEqualTo("caseId",request.getCaseId()).andEqualTo("status","1");
        List<CaseReasonMainRecord> caseReasonMainRecords=caseReasonMainRecordMapper.selectByExample(example);
        if(null!=caseReasonMainRecords&&caseReasonMainRecords.size()>0){
            CaseReasonMainRecord caseReasonMainRecord=caseReasonMainRecords.get(0);
            informInvestigationEndFormVo.setCaseReason(caseReasonMainRecord.getCaseReasonName());
            informInvestigationEndFormVo.setCaseReasonCode(caseReasonMainRecord.getCaseReasonCode());
            informInvestigationEndFormVo.setCaseReasonNodeid(caseReasonMainRecord.getCaseReasonNodeid());
            informInvestigationEndFormVo.setClaimId(caseReasonMainRecord.getClaimId());
            List<ViolateRuleInfo> violateRuleInfos=new ArrayList<>();
            List<PunishRuleInfo> punishRuleInfos=new ArrayList<>();
            for (CaseReasonMainRecord caseReasonMain:caseReasonMainRecords) {
                ViolateRuleInfo violateRuleInfo=new ViolateRuleInfo();
                violateRuleInfo.setIllegalBasis(caseReasonMain.getIllegalBasis());
                violateRuleInfo.setIllegalDetail(caseReasonMain.getIllegalDetail());
                violateRuleInfos.add(violateRuleInfo);
                PunishRuleInfo punishRuleInfo=new PunishRuleInfo();
                punishRuleInfo.setPunishBasis(caseReasonMain.getPunishBasis());
                punishRuleInfo.setPunishDetail(caseReasonMain.getPunishDetail());
                punishRuleInfos.add(punishRuleInfo);
            }
            informInvestigationEndFormVo.setViolateRuleInfos(violateRuleInfos);
            informInvestigationEndFormVo.setPunishRuleInfos(punishRuleInfos);
        }
        //获取案件主表相关数据
        CaseMainInfoVo caseMainInfoVo=caseMainInfoService.getCaseMainInfo(request.getCaseId());
        informInvestigationEndFormVo.setCaseName(caseMainInfoVo.getCaseName());
        CaseMainDetailInfo caseMainDetailInfo=caseMainDetailInfoService.getCaseMainDetailByCaseId(request.getCaseId());
        informInvestigationEndFormVo.setIllegalSituation(caseMainDetailInfo.getIllegalSituation());
        informInvestigationEndFormVo.setIllegalLevel(caseMainDetailInfo.getIllegalLevel());
        informInvestigationEndFormVo.setPunishKinds(caseMainDetailInfo.getPunishKinds());
        informInvestigationEndFormVo.setDiscretionInterval(caseMainDetailInfo.getDiscretionInterval());
        informInvestigationEndFormVo.setDraftPunishMoney(caseMainDetailInfo.getDraftPunishMoney());
        informInvestigationEndFormVo.setPunishContent(caseMainDetailInfo.getPunishContent());
        informInvestigationEndFormVo.setIsImportantCase(caseMainDetailInfo.getIsImportantCase());
        informInvestigationEndFormVo.setIsNeedCollectiveDiscuss(caseMainDetailInfo.getIsNeedCollectiveDiscuss());
        informInvestigationEndFormVo.setConfiscateIllegalMoney(caseMainDetailInfo.getConfiscateIllegalMoney());
        informInvestigationEndFormVo.setConfiscateIllegalProperty(caseMainDetailInfo.getConfiscateIllegalProperty());
        informInvestigationEndFormVo.setInvestConclusion(caseMainDetailInfo.getInvestConclusion());
        informInvestigationEndFormVo.setNotGivePunishReason(caseMainDetailInfo.getNotGivePunishReason());
        informInvestigationEndFormVo.setNotGivePunishDetail(caseMainDetailInfo.getNotGivePunishDetail());
        //查询附件信息
        Example appendixExample=new Example(CaseAppendixRecord.class);
        appendixExample.createCriteria().andEqualTo("caseId",request.getCaseId()).andEqualTo("documentCatalogCode",request.getDocumentCatalogCode()).andEqualTo("isDelete","0");
        List<CaseAppendixRecord> caseAppendixRecords=caseAppendixRecordMapper.selectByExample(appendixExample);
        List<AppendixDto> appendixList=new ArrayList<>();
        for (CaseAppendixRecord caseAppendixRecord:caseAppendixRecords) {
            AppendixDto appendixDto=new AppendixDto();
            appendixDto.setAppendixName(caseAppendixRecord.getAppendixName());
            appendixDto.setAppendixTypeId(caseAppendixRecord.getAppendixTypeId());
            appendixDto.setAppendixUrl(caseAppendixRecord.getAppendixUrl());
            appendixList.add(appendixDto);
        }
        informInvestigationEndFormVo.setAppendixList(appendixList);
        return Result.success(informInvestigationEndFormVo);*/
        return Result.success(informInvestigationEndFormVo);
    }

    /**
     * 组装调查终结VO
     *
     * @param casePartiesReasonType
     * @param handleType
     * @param caseMainInfo
     * @param caseMainDetailInfo
     * @return {@link InformInvestigationEndFormVo}
     * @author liyafeng
     * @date 2022/5/18
     */
    private InformInvestigationEndFormVo formInformInvestigationEndFormVo(String caseId, String documentCatalogCode, String casePartiesReasonType, String handleType, CaseMainInfo caseMainInfo, CaseMainDetailInfo caseMainDetailInfo) {
        InformInvestigationEndFormVo vo = new InformInvestigationEndFormVo();
        vo.setDiscussConclusion(caseMainDetailInfo.getDiscussConclusion());
        vo.setCasePartiesReasonType(casePartiesReasonType);
        vo.setHandleType(handleType);
        vo.setCaseName(caseMainInfo.getCaseName());
        vo.setCaseProceedTime(caseMainDetailInfo.getCaseProceedTime());
        vo.setHandleConclusion(caseMainDetailInfo.getHandleConclusion());
        String personReasonId = caseMainDetailInfo.getPersonReasonId();
        List<List<String>> arrayList = new ArrayList<>();
        if (StringUtils.isNotBlank(personReasonId)) {
            List<PersonReasonIds> lists = JSON.parseArray(personReasonId, PersonReasonIds.class);
            if (!ObjectUtils.isEmpty(lists)) {
                for (PersonReasonIds list : lists) {
                    List<String> caseReasonIds = list.getCaseReasonIds();
                    arrayList.add(caseReasonIds);
                }
            }
            vo.setPersonReasonId(arrayList);
        }
        vo.setPersonReasonName(caseMainDetailInfo.getPersonReasonName());
        //应急案由处理
        if (!ObjectUtils.isEmpty(caseMainDetailInfo.getCaseEmergencyReasonContent())) {
            List<CaseEmergencyReasonInfoDto> caseEmergencyReasonList = JSON.parseArray(caseMainDetailInfo.getCaseEmergencyReasonContent(), CaseEmergencyReasonInfoDto.class);
            vo.setCaseEmergencyReasonList(caseEmergencyReasonList);
        }
        if (Constant.STRING_1.equals(casePartiesReasonType)) {
            //单案由单当事人 处置方式默认是 常规处罚
            Example example = new Example(CaseReasonMainRecord.class);
            example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status", "1");
            List<CaseReasonMainRecord> caseReasonMainRecords = caseReasonMainRecordMapper.selectByExample(example);
            if (null != caseReasonMainRecords && caseReasonMainRecords.size() > 0) {
                CaseReasonMainRecord caseReasonMainRecord = caseReasonMainRecords.get(0);
                vo.setCaseReason(caseReasonMainRecord.getCaseReasonName());
                vo.setCaseReasonCode(caseReasonMainRecord.getCaseReasonCode());
                vo.setCaseReasonNodeid(caseReasonMainRecord.getCaseReasonNodeid());
                vo.setClaimId(caseReasonMainRecord.getClaimId());
                List<ViolateRuleInfo> violateRuleInfos = new ArrayList<>();
                List<PunishRuleInfo> punishRuleInfos = new ArrayList<>();
                ViolateRuleInfo violateRuleInfo = new ViolateRuleInfo();
                violateRuleInfo.setIllegalBasis(caseReasonMainRecord.getIllegalBasis());
                violateRuleInfo.setIllegalDetail(caseReasonMainRecord.getIllegalDetail());
                violateRuleInfos.add(violateRuleInfo);
                PunishRuleInfo punishRuleInfo = new PunishRuleInfo();
                punishRuleInfo.setPunishBasis(caseReasonMainRecord.getPunishBasis());
                punishRuleInfo.setPunishDetail(caseReasonMainRecord.getPunishDetail());
                punishRuleInfos.add(punishRuleInfo);
                vo.setViolateRuleInfos(violateRuleInfos);
                vo.setPunishRuleInfos(punishRuleInfos);
            }
            // 获取立案调查终结处理内容
            Example auxiliaryExample = new Example(CaseMainDetailAuxiliaryInfo.class);
            auxiliaryExample.createCriteria().andEqualTo("caseId", caseId);
            List<CaseMainDetailAuxiliaryInfo> caseMainDetailAuxiliaryInfos = caseMainDetailAuxiliaryInfoMapper.selectByExample(auxiliaryExample);
            if (CollectionUtil.isNotEmpty(caseMainDetailAuxiliaryInfos)) {
                CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = caseMainDetailAuxiliaryInfos.get(0);
                vo.setDisposeContext(caseMainDetailAuxiliaryInfo.getDisposeContext());
            }
            //获取案件主表相关数据
            //BeanUtils.copyProperties(caseMainDetailInfo,vo);
            vo.setIllegalSituation(caseMainDetailInfo.getIllegalSituation());
            vo.setIllegalLevel(caseMainDetailInfo.getIllegalLevel());
            vo.setPunishKinds(caseMainDetailInfo.getPunishKinds());
            vo.setDiscretionInterval(caseMainDetailInfo.getDiscretionInterval());
            vo.setDraftPunishMoney(caseMainDetailInfo.getDraftPunishMoney());
            vo.setPunishContent(caseMainDetailInfo.getPunishContent());
            vo.setIsImportantCase(caseMainDetailInfo.getIsImportantCase());
            vo.setIsNeedCollectiveDiscuss(caseMainDetailInfo.getIsNeedCollectiveDiscuss());
            vo.setConfiscateIllegalMoney(caseMainDetailInfo.getConfiscateIllegalMoney());
            vo.setConfiscateIllegalProperty(caseMainDetailInfo.getConfiscateIllegalProperty());
            vo.setConfiscateIllegalPropertyValue(caseMainDetailInfo.getConfiscateIllegalPropertyValue());
            vo.setInvestConclusion(caseMainDetailInfo.getInvestConclusion());
            vo.setNotGivePunishReason(caseMainDetailInfo.getNotGivePunishReason());
            vo.setNotGivePunishDetail(caseMainDetailInfo.getNotGivePunishDetail());
            vo.setCaseInvestigateTime(caseMainDetailInfo.getCaseInvestigateTime());
            //查询附件信息
            Example appendixExample = new Example(CaseAppendixRecord.class);
            appendixExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("isDelete", "0");
            List<CaseAppendixRecord> caseAppendixRecords = caseAppendixRecordMapper.selectByExample(appendixExample);
            List<AppendixDto> appendixList = new ArrayList<>();
            for (CaseAppendixRecord caseAppendixRecord : caseAppendixRecords) {
                AppendixDto appendixDto = new AppendixDto();
                appendixDto.setAppendixName(caseAppendixRecord.getAppendixName());
                appendixDto.setAppendixTypeId(caseAppendixRecord.getAppendixTypeId());
                appendixDto.setAppendixUrl(caseAppendixRecord.getAppendixUrl());
                appendixList.add(appendixDto);
            }
            vo.setAppendixList(appendixList);
        } else if (Constant.STRING_2.equals(casePartiesReasonType)) {
            //多案由单当事人 默认合并处罚
            List<InvestEndMultiple> investEndMultipleList = new ArrayList<>();
            //1.循环案由 组装InvestEndMultiple
            Example example = new Example(CaseReasonMainRecord.class);
            example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status", "1");
            List<CaseReasonMainRecord> caseReasonMainRecords = caseReasonMainRecordMapper.selectByExample(example);
            if (null != caseReasonMainRecords && caseReasonMainRecords.size() > 0) {
                for (CaseReasonMainRecord caseReasonMainRecord : caseReasonMainRecords) {
                    InvestEndMultiple investEndMultiple = new InvestEndMultiple();
                    investEndMultiple.setCaseReason(caseReasonMainRecord.getCaseReasonName());
                    investEndMultiple.setCaseReasonCode(caseReasonMainRecord.getCaseReasonCode());
                    investEndMultiple.setCaseReasonNodeid(caseReasonMainRecord.getCaseReasonNodeid());
                    investEndMultiple.setClaimId(caseReasonMainRecord.getClaimId());
                    List<ViolateRuleInfo> violateRuleInfos = new ArrayList<>();
                    List<PunishRuleInfo> punishRuleInfos = new ArrayList<>();
                    ViolateRuleInfo violateRuleInfo = new ViolateRuleInfo();
                    violateRuleInfo.setIllegalBasis(caseReasonMainRecord.getIllegalBasis());
                    violateRuleInfo.setIllegalDetail(caseReasonMainRecord.getIllegalDetail());
                    violateRuleInfos.add(violateRuleInfo);
                    PunishRuleInfo punishRuleInfo = new PunishRuleInfo();
                    punishRuleInfo.setPunishBasis(caseReasonMainRecord.getPunishBasis());
                    punishRuleInfo.setPunishDetail(caseReasonMainRecord.getPunishDetail());
                    punishRuleInfos.add(punishRuleInfo);
                    investEndMultiple.setViolateRuleInfos(violateRuleInfos);
                    investEndMultiple.setPunishRuleInfos(punishRuleInfos);
                    investEndMultiple.setTerritoryCode(caseReasonMainRecord.getTerritoryCode());
                    investEndMultiple.setItemVersionCode(caseReasonMainRecord.getItemVersionCode());
                    //根据案由id、caseid获取 案件
                    //查询案件详情补充表
                    Example auxiliaryExample = new Example(CaseMainDetailAuxiliaryInfo.class);
                    auxiliaryExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("caseReasonId", caseReasonMainRecord.getId());
                    List<CaseMainDetailAuxiliaryInfo> caseMainDetailAuxiliaryInfos = caseMainDetailAuxiliaryInfoMapper.selectByExample(auxiliaryExample);
                    if (null != caseMainDetailAuxiliaryInfos && caseMainDetailAuxiliaryInfos.size() > 0) {
                        CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = caseMainDetailAuxiliaryInfos.get(0);
                        investEndMultiple.setId(caseMainDetailAuxiliaryInfo.getId());
                        BeanUtils.copyProperties(caseMainDetailAuxiliaryInfo, investEndMultiple);
                        Example appendixExample = new Example(CaseAppendixRecord.class);
                        appendixExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("isDelete", "0").andEqualTo("caseReasonId", caseReasonMainRecord.getId());
                        List<CaseAppendixRecord> caseAppendixRecords = caseAppendixRecordMapper.selectByExample(appendixExample);
                        List<AppendixDto> appendixList = new ArrayList<>();
                        for (CaseAppendixRecord caseAppendixRecord : caseAppendixRecords) {
                            AppendixDto appendixDto = new AppendixDto();
                            appendixDto.setAppendixName(caseAppendixRecord.getAppendixName());
                            appendixDto.setAppendixTypeId(caseAppendixRecord.getAppendixTypeId());
                            appendixDto.setAppendixUrl(caseAppendixRecord.getAppendixUrl());
                            appendixList.add(appendixDto);
                        }
                        investEndMultiple.setAppendixList(appendixList);
                    }
                    investEndMultipleList.add(investEndMultiple);
                }
            }
            vo.setInvestEndMultipleList(investEndMultipleList);
            //BeanUtils.copyProperties(caseMainDetailInfo,vo);
            vo.setIllegalSituation(caseMainDetailInfo.getIllegalSituation());
            vo.setIllegalLevel(caseMainDetailInfo.getIllegalLevel());
            vo.setPunishKinds(caseMainDetailInfo.getPunishKinds());
            vo.setDiscretionInterval(caseMainDetailInfo.getDiscretionInterval());
            vo.setDraftPunishMoney(caseMainDetailInfo.getDraftPunishMoney());
            vo.setPunishContent(caseMainDetailInfo.getPunishContent());
            vo.setIsImportantCase(caseMainDetailInfo.getIsImportantCase());
            vo.setIsNeedCollectiveDiscuss(caseMainDetailInfo.getIsNeedCollectiveDiscuss());
            vo.setConfiscateIllegalMoney(caseMainDetailInfo.getConfiscateIllegalMoney());
            vo.setConfiscateIllegalProperty(caseMainDetailInfo.getConfiscateIllegalProperty());
            vo.setConfiscateIllegalPropertyValue(caseMainDetailInfo.getConfiscateIllegalPropertyValue());
            vo.setInvestConclusion(caseMainDetailInfo.getInvestConclusion());
            vo.setNotGivePunishReason(caseMainDetailInfo.getNotGivePunishReason());
            vo.setNotGivePunishDetail(caseMainDetailInfo.getNotGivePunishDetail());
            //涉刑移送
            if (Constant.STRING_1.equals(caseMainDetailInfo.getHandleConclusion())) {
                Example appendixExample = new Example(CaseAppendixRecord.class);
                appendixExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("isDelete", "0");
                List<CaseAppendixRecord> caseAppendixRecords = caseAppendixRecordMapper.selectByExample(appendixExample);
                List<AppendixDto> appendixList = new ArrayList<>();
                for (CaseAppendixRecord caseAppendixRecord : caseAppendixRecords) {
                    AppendixDto appendixDto = new AppendixDto();
                    appendixDto.setAppendixName(caseAppendixRecord.getAppendixName());
                    appendixDto.setAppendixTypeId(caseAppendixRecord.getAppendixTypeId());
                    appendixDto.setAppendixUrl(caseAppendixRecord.getAppendixUrl());
                    appendixList.add(appendixDto);
                }
                vo.setAppendixList(appendixList);
            }
        } else if (Constant.STRING_3.equals(casePartiesReasonType)) {
            //单案由多当事人
            Example example = new Example(CaseReasonMainRecord.class);
            example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status", "1");
            List<CaseReasonMainRecord> caseReasonMainRecords = caseReasonMainRecordMapper.selectByExample(example);
            if (null != caseReasonMainRecords && caseReasonMainRecords.size() > 0) {
                CaseReasonMainRecord caseReasonMainRecord = caseReasonMainRecords.get(0);
                vo.setCaseReason(caseReasonMainRecord.getCaseReasonName());
                vo.setCaseReasonCode(caseReasonMainRecord.getCaseReasonCode());
                vo.setCaseReasonNodeid(caseReasonMainRecord.getCaseReasonNodeid());
                vo.setClaimId(caseReasonMainRecord.getClaimId());
                List<ViolateRuleInfo> violateRuleInfos = new ArrayList<>();
                List<PunishRuleInfo> punishRuleInfos = new ArrayList<>();
                ViolateRuleInfo violateRuleInfo = new ViolateRuleInfo();
                violateRuleInfo.setIllegalBasis(caseReasonMainRecord.getIllegalBasis());
                violateRuleInfo.setIllegalDetail(caseReasonMainRecord.getIllegalDetail());
                violateRuleInfos.add(violateRuleInfo);
                PunishRuleInfo punishRuleInfo = new PunishRuleInfo();
                punishRuleInfo.setPunishBasis(caseReasonMainRecord.getPunishBasis());
                punishRuleInfo.setPunishDetail(caseReasonMainRecord.getPunishDetail());
                punishRuleInfos.add(punishRuleInfo);
                vo.setViolateRuleInfos(violateRuleInfos);
                vo.setPunishRuleInfos(punishRuleInfos);
            }
            List<InvestEndMultiple> investEndMultipleList = new ArrayList<>();
            //查询当事人表
            List<CasePartiesRecordVo> casePartiesRecords = casePartiesRecordService.getCasePartiesInfo(caseId);
            for (CasePartiesRecordVo casePartiesRecord : casePartiesRecords) {
                //根据当事人id、案件id查询 案件详情补充表
                Example auxiliaryExample = new Example(CaseMainDetailAuxiliaryInfo.class);
                auxiliaryExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("partyId", casePartiesRecord.getPartyId());
                List<CaseMainDetailAuxiliaryInfo> caseMainDetailAuxiliaryInfos = caseMainDetailAuxiliaryInfoMapper.selectByExample(auxiliaryExample);
                if (null != caseMainDetailAuxiliaryInfos && caseMainDetailAuxiliaryInfos.size() > 0) {
                    InvestEndMultiple investEndMultiple = new InvestEndMultiple();
                    CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = caseMainDetailAuxiliaryInfos.get(0);
                    BeanUtils.copyProperties(caseMainDetailAuxiliaryInfo, investEndMultiple);
                    investEndMultiple.setId(caseMainDetailAuxiliaryInfo.getId());
                    Example appendixExample = new Example(CaseAppendixRecord.class);
                    appendixExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("isDelete", "0").andEqualTo("partyId", casePartiesRecord.getPartyId());
                    List<CaseAppendixRecord> caseAppendixRecords = caseAppendixRecordMapper.selectByExample(appendixExample);
                    List<AppendixDto> appendixList = new ArrayList<>();
                    for (CaseAppendixRecord caseAppendixRecord : caseAppendixRecords) {
                        AppendixDto appendixDto = new AppendixDto();
                        appendixDto.setAppendixName(caseAppendixRecord.getAppendixName());
                        appendixDto.setAppendixTypeId(caseAppendixRecord.getAppendixTypeId());
                        appendixDto.setAppendixUrl(caseAppendixRecord.getAppendixUrl());
                        appendixList.add(appendixDto);
                    }
                    investEndMultiple.setAppendixList(appendixList);
                    investEndMultipleList.add(investEndMultiple);
                }
            }
            vo.setInvestEndMultipleList(investEndMultipleList);
            //BeanUtils.copyProperties(caseMainDetailInfo,vo);
            vo.setIllegalSituation(caseMainDetailInfo.getIllegalSituation());
            vo.setIllegalLevel(caseMainDetailInfo.getIllegalLevel());
            vo.setPunishKinds(caseMainDetailInfo.getPunishKinds());
            vo.setDiscretionInterval(caseMainDetailInfo.getDiscretionInterval());
            vo.setDraftPunishMoney(caseMainDetailInfo.getDraftPunishMoney());
            vo.setPunishContent(caseMainDetailInfo.getPunishContent());
            vo.setIsImportantCase(caseMainDetailInfo.getIsImportantCase());
            vo.setIsNeedCollectiveDiscuss(caseMainDetailInfo.getIsNeedCollectiveDiscuss());
            vo.setConfiscateIllegalMoney(caseMainDetailInfo.getConfiscateIllegalMoney());
            vo.setConfiscateIllegalProperty(caseMainDetailInfo.getConfiscateIllegalProperty());
            vo.setConfiscateIllegalPropertyValue(caseMainDetailInfo.getConfiscateIllegalPropertyValue());
            vo.setInvestConclusion(caseMainDetailInfo.getInvestConclusion());
            vo.setNotGivePunishReason(caseMainDetailInfo.getNotGivePunishReason());
            vo.setNotGivePunishDetail(caseMainDetailInfo.getNotGivePunishDetail());
            if (Constant.STRING_1.equals(handleType) || Constant.STRING_1.equals(caseMainDetailInfo.getHandleConclusion())) {
                Example appendixExample = new Example(CaseAppendixRecord.class);
                appendixExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("isDelete", "0");
                List<CaseAppendixRecord> caseAppendixRecords = caseAppendixRecordMapper.selectByExample(appendixExample);
                List<AppendixDto> appendixList = new ArrayList<>();
                for (CaseAppendixRecord caseAppendixRecord : caseAppendixRecords) {
                    AppendixDto appendixDto = new AppendixDto();
                    appendixDto.setAppendixName(caseAppendixRecord.getAppendixName());
                    appendixDto.setAppendixTypeId(caseAppendixRecord.getAppendixTypeId());
                    appendixDto.setAppendixUrl(caseAppendixRecord.getAppendixUrl());
                    appendixList.add(appendixDto);
                }
                vo.setAppendixList(appendixList);
            }
        }
        return vo;
    }

    /**
     * 保存表单数据-调查终结
     *
     * @param informInvestigationEndFormDto
     * @return {@link Result< String>}
     * @author liyafeng
     * @date 2022/2/25
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public Result<String> saveInformInvestigationEndForm(InformInvestigationEndFormDto informInvestigationEndFormDto) {
        //校验违则
        checkCaseReasonViolateRuleAndPunishRule(informInvestigationEndFormDto);
        if (caseInfoAdjustRecordService.isExistUndoneAdjustPartyRecord(informInvestigationEndFormDto.getCaseId())) {
            throw new BusinessException("请操作完调整当事人步骤（审批通过或删除调整当事人审批表）");
        }
        // 校验处罚金额是否满足裁量规则
        checkAmount(informInvestigationEndFormDto);
        //保存案由调整记录
        boolean caseReasonIsChange = saveAdjustInfoWithCaseReason(informInvestigationEndFormDto);
        // 人设的案由不为空的时候修改人设的案由
        if (!ObjectUtils.isEmpty(informInvestigationEndFormDto.getPersonReasonIds())) {
            Example example = new Example(CaseMainDetailInfo.class);
            example.createCriteria().andEqualTo("caseId", informInvestigationEndFormDto.getCaseId());
            CaseMainDetailInfo caseMainDetailInfo = new CaseMainDetailInfo();
            caseMainDetailInfo.setPersonReasonId(JSON.toJSONString(informInvestigationEndFormDto.getPersonReasonIds()));
            caseMainDetailInfo.setPersonReasonName(informInvestigationEndFormDto.getPersonReasonNames().stream().collect(Collectors.joining(",")));
            caseMainDetailInfoMapper.updateByExampleSelective(caseMainDetailInfo, example);
        }
        //处理结论handleConclusion发生变化时删除之前保存的文书
        dealInvestigationDocument(informInvestigationEndFormDto);

        //判断案件是否是公安退回, 退回的案件不允许再次发起涉刑移送
        checkCaseIsCriminalBack(informInvestigationEndFormDto);

        String casePartiesReasonType = informInvestigationEndFormDto.getCasePartiesReasonType();
        if (Constant.STRING_1.equals(casePartiesReasonType)) {
            //单案由单当事人 保存
            saveSingleCaseReasonAndParty(informInvestigationEndFormDto);
        } else if (Constant.STRING_2.equals(casePartiesReasonType)) {
            //多案由单当事人 保存
            saveMultipleCaseReason(informInvestigationEndFormDto);
        } else if (Constant.STRING_3.equals(casePartiesReasonType)) {
            //单案由多当事人 保存
            saveMultipleParty(informInvestigationEndFormDto);
        }
        //如果案由有变动，则需要插入一条变动记录
        if (caseReasonIsChange) {
            UserDTO userInfo = UserUtil.getUserInfo();
            String userId = "";
            if (userInfo != null) {
                userId = String.valueOf(userInfo.getUserId());
            }
            //当事人更新成功后，生成一条记录，然后定时重新上报已经上报成功的数据
            caseDataChangeReportRecordService.save(informInvestigationEndFormDto.getCaseId(), CaseChangeOperationTypeEnum.OPERATION_TYPE_4.getCode(), userId);
        }
        return Result.success("保存成功");
    }

    /**
     * 检查处罚金额是否满足裁量信息
     * @param dto
     */
    private void checkAmount(InformInvestigationEndFormDto dto) {
        // 不予处罚不校验
        if (Constant.STRING_2.equals(dto.getInvestConclusion())) {
            return;
        }
        // 案件案由、当事人类型
        String casePartiesReasonType = dto.getCasePartiesReasonType();
        // 处置方式
        String handleType = dto.getHandleType();
        // 单当事人单案由 && 有罚款
        if (Constant.STRING_1.equals(casePartiesReasonType) && dto.getPunishKinds().contains(PunishKindsEnum.PunishKind_2.getDes())) {
            structureSingletonCompareForInformInvestigationEnd(dto);
        }
        // 多案由单当事人
        if (Constant.STRING_2.equals(casePartiesReasonType)) {
            structureCompareForInformInvestigationEnd(dto);
        }
        // 单案由多当事人 合并处罚 罚款
        if (Constant.STRING_3.equals(casePartiesReasonType) 
                && Constant.STRING_1.equals(handleType) 
                && dto.getPunishKinds().contains(PunishKindsEnum.PunishKind_2.getDes())) {
            structureSingletonCompareForInformInvestigationEnd(dto);
        }
        // 单案由多当事人 分别处罚
        if (Constant.STRING_3.equals(casePartiesReasonType) && Constant.STRING_2.equals(handleType)){
            structureCompareForInformInvestigationEnd(dto);
        }

    }

    /**
     * 多案由单当事人 或 单案由多当事人分别处罚 的裁量参数组装
     */
    private void structureCompareForInformInvestigationEnd(InformInvestigationEndFormDto dto) {
        // 裁量校验参数初始化
        CompareDiscretionDto compareParam = new CompareDiscretionDto();
        // 组装校验参数
        List<InvestEndMultiple> investEndMultipleList = dto.getInvestEndMultipleList();
        List<String> discretionIds = investEndMultipleList.stream()
                .filter(r -> r.getPunishKinds().contains(PunishKindsEnum.PunishKind_2.getDes()) && StrUtil.isNotBlank(r.getIllegalSituation()))
                .map(InvestEndMultiple::getIllegalSituation).collect(Collectors.toList());
        Map<String, String> punishInfoMap = investEndMultipleList.stream()
                .filter(r -> r.getPunishKinds().contains(PunishKindsEnum.PunishKind_2.getDes()) && StrUtil.isNotBlank(r.getIllegalSituation()))
                .collect(Collectors.toMap(InvestEndMultiple::getIllegalSituation, InvestEndMultiple::getDraftPunishMoney));
        compareParam.setDiscretionRuleHisIds(discretionIds);
        compareParam.setPunishInfoMap(punishInfoMap);
        configOrgRegulatoryDiscretionRuleHisService.verifyDiscretionAmount(compareParam);
    }

    /**
     * 单当事人单案由 或 单案由多当事人合并处罚 的裁量参数组装
     */
    private void structureSingletonCompareForInformInvestigationEnd(InformInvestigationEndFormDto dto) {
        if (StrUtil.isBlank(dto.getIllegalSituation())){
            return;
        }
        CompareSingleDiscretionDto param = new CompareSingleDiscretionDto(dto.getIllegalSituation(), dto.getDraftPunishMoney());
        configOrgRegulatoryDiscretionRuleHisService.verifySingleDiscretionAmount(param);
    }


    /**
     * 单案由 多当事人保存
     *
     * @param informInvestigationEndFormDto
     * @return
     * @author liyafeng
     * @date 2022/5/19
     */
    private void saveMultipleParty(InformInvestigationEndFormDto informInvestigationEndFormDto) {
        //1.更新案件主表 处置方式
        String handleType = informInvestigationEndFormDto.getHandleType();
        editCaseMainInfo(informInvestigationEndFormDto, handleType);
        //删除附件
        caseAppendixRecordService.removeCaseAppendixRecordByCaseIdAndCatalogCode(informInvestigationEndFormDto.getCaseId(), informInvestigationEndFormDto.getDocCatalogCode());
        //2.更新案由表 并 插入案件详情补充表
        //无效案由原有数据
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("caseId", informInvestigationEndFormDto.getCaseId());
        caseReasonMainRecordMapper.updateCaseReasonMainRecordStatus(paramMap);
        //新增案由表数据
        String caseReasonRecordId = saveCaseResonRecordByDto(informInvestigationEndFormDto);
        List<InvestEndMultiple> investEndMultipleList = informInvestigationEndFormDto.getInvestEndMultipleList();
        for (InvestEndMultiple investEndMultiple : investEndMultipleList) {
            if (Constant.STRING_1.equals(handleType)) {
                //合并处罚--将原来的数据更新为空
                CaseMainDetailAuxiliaryInfo updateCaseMainDetailAuxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
                updateCaseMainDetailAuxiliaryInfo.setId(investEndMultiple.getId());
                updateCaseMainDetailAuxiliaryInfo.setIllegalSituation("");
                updateCaseMainDetailAuxiliaryInfo.setPunishKinds("");
                updateCaseMainDetailAuxiliaryInfo.setDiscretionInterval("");
                updateCaseMainDetailAuxiliaryInfo.setDraftPunishMoney("");
                updateCaseMainDetailAuxiliaryInfo.setPunishContent("");
                updateCaseMainDetailAuxiliaryInfo.setIllegalLevel("");
                updateCaseMainDetailAuxiliaryInfo.setConfiscateIllegalProperty("");
                updateCaseMainDetailAuxiliaryInfo.setConfiscateIllegalMoney("");
                updateCaseMainDetailAuxiliaryInfo.setInvestConclusion("");
                updateCaseMainDetailAuxiliaryInfo.setNotGivePunishReason("");
                updateCaseMainDetailAuxiliaryInfo.setNotGivePunishDetail("");
                caseMainDetailAuxiliaryInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailAuxiliaryInfo);
            } else {
                //分别处罚--根据id更新案件详情补充表
                CaseMainDetailAuxiliaryInfo updateCaseMainDetailAuxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
                BeanUtils.copyProperties(investEndMultiple, updateCaseMainDetailAuxiliaryInfo);
                updateCaseMainDetailAuxiliaryInfo.setId(investEndMultiple.getId());
                updateCaseMainDetailAuxiliaryInfo.setCaseReasonId(caseReasonRecordId);
                updateCaseMainDetailAuxiliaryInfo.setCaseReasonName(investEndMultiple.getCaseReason());
                //分别处罚-更新处罚内容为处罚建议
                String punishSuggestion = getPunishSuggestionStrByInvestEndMultiple(investEndMultiple);
                updateCaseMainDetailAuxiliaryInfo.setPunishContent(punishSuggestion);
                updateCaseMainDetailAuxiliaryInfo.setPunishOpinion(punishSuggestion);
                caseMainDetailAuxiliaryInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailAuxiliaryInfo);
            }
            //4.附件保存
            saveAppendixDto(informInvestigationEndFormDto.getCaseId(), informInvestigationEndFormDto.getDocCatalogCode(), investEndMultiple.getId(), investEndMultiple.getAppendixList());
        }
        //合并处罚
        if (Constant.STRING_1.equals(handleType)) {
            CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(informInvestigationEndFormDto.getCaseId());
            List<AppendixDto> list = informInvestigationEndFormDto.getAppendixList();
            if (!ObjectUtils.isEmpty(list)) {
                for (int i = 0; i < list.size(); i++) {
                    CaseAppendixRecord record = new CaseAppendixRecord();
                    record.setCaseId(informInvestigationEndFormDto.getCaseId());
                    record.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
                    record.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
                    record.setAppendixUrl(informInvestigationEndFormDto.getAppendixList().get(i).getAppendixUrl());
                    record.setAppendixTypeId(informInvestigationEndFormDto.getAppendixList().get(i).getAppendixTypeId());
                    record.setAppendixName(informInvestigationEndFormDto.getAppendixList().get(i).getAppendixName());
                    record.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
                    record.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
                    record.setDocumentCatalogCode(informInvestigationEndFormDto.getDocCatalogCode());
                    caseAppendixRecordService.saveCaseAppendixRecord(record);
                }
            }
        }
        //3.更新案件详情表
        editCaseMainDetailInfo(informInvestigationEndFormDto, handleType, Constant.STRING_3);
        //涉刑移送附件保存处理
        if (Constant.STRING_1.equals(informInvestigationEndFormDto.getHandleConclusion())) {
            saveCaseAppendixRecord(informInvestigationEndFormDto);
        }
    }

    private String getPunishSuggestionStrByInvestEndMultiple(InvestEndMultiple investEndMultiple) {
        String investConclusion = investEndMultiple.getInvestConclusion();
        String punishKinds = investEndMultiple.getPunishKinds();
        String punishSuggestion = "";
        String sequenceNumber = "";
        String punctuation = "；";
        if (Constant.STRING_1.equals(investConclusion)) {
            //予以处罚
            String[] punishKindsArr = punishKinds.split(",");
            for (int i = 1; i <= punishKindsArr.length; i++) {
                String punishKind = punishKindsArr[i - 1];
                if (punishKindsArr.length > 1) {
                    sequenceNumber = i + "、";
                }
                if (i == punishKindsArr.length) {
                    punctuation = "";
                }
                if ("罚款".equals(punishKind)) {
                    punishSuggestion = punishSuggestion + sequenceNumber + "处罚款人民币" + ConvertUpMoneyUtil.toChinese(investEndMultiple.getDraftPunishMoney()) + "整（¥" + investEndMultiple.getDraftPunishMoney() + ")" + punctuation;
                } else if ("没收违法所得、没收非法财物".equals(punishKind)) {
                    String value = investEndMultiple.getConfiscateIllegalPropertyValue();
                    if (StringUtils.isNotBlank(investEndMultiple.getConfiscateIllegalMoney()) && StringUtils.isBlank(investEndMultiple.getConfiscateIllegalProperty())) {
                        punishSuggestion = punishSuggestion + sequenceNumber + "没收违法所得人民币" + ConvertUpMoneyUtil.toChinese(investEndMultiple.getConfiscateIllegalMoney()) + "整（¥" + investEndMultiple.getConfiscateIllegalMoney() + ")" + punctuation;
                    }
                    if (StringUtils.isBlank(investEndMultiple.getConfiscateIllegalMoney()) && StringUtils.isNotBlank(investEndMultiple.getConfiscateIllegalProperty())) {
                        if (StringUtils.isNotBlank(value)) {
                            punishSuggestion = punishSuggestion + sequenceNumber + "没收违法财物包括" + investEndMultiple.getConfiscateIllegalProperty() + "（价值¥" + value + "）" + punctuation;
                        } else {
                            punishSuggestion = punishSuggestion + sequenceNumber + "没收违法财物包括" + investEndMultiple.getConfiscateIllegalProperty() + punctuation;
                        }
                    }
                    if (StringUtils.isNotBlank(investEndMultiple.getConfiscateIllegalMoney()) && StringUtils.isNotBlank(investEndMultiple.getConfiscateIllegalProperty())) {
                        punishSuggestion = punishSuggestion + sequenceNumber + "没收违法所得人民币" + ConvertUpMoneyUtil.toChinese(investEndMultiple.getConfiscateIllegalMoney()) + "整（¥" + investEndMultiple.getConfiscateIllegalMoney() + ")，没收违法财物包括" + investEndMultiple.getConfiscateIllegalProperty() + punctuation;
                    }
                } else if ("没收非法财物".equals(punishKind)) {
                    if (StringUtils.isNotBlank(investEndMultiple.getConfiscateIllegalPropertyValue())) {
                        punishSuggestion = punishSuggestion + sequenceNumber + "没收违法财物包括" + investEndMultiple.getConfiscateIllegalProperty() + "（价值¥" + investEndMultiple.getConfiscateIllegalPropertyValue() + "）" + punctuation;
                    } else {
                        punishSuggestion = punishSuggestion + sequenceNumber + "没收违法财物包括" + investEndMultiple.getConfiscateIllegalProperty() + punctuation;
                    }
                } else {
                    punishSuggestion = punishSuggestion + sequenceNumber + punishKind + punctuation;
                }
            }
            return punishSuggestion;
        } else if (Constant.STRING_2.equals(investConclusion)) {
            //不予处罚
            punishSuggestion = "不予处罚";
            return punishSuggestion;
        }
        return punishSuggestion;
    }

    /**
     * 更新案件详情表
     *
     * @param informInvestigationEndFormDto
     * @param handleType
     * @return
     * @author liyafeng
     * @date 2022/5/19
     */
    private void editCaseMainDetailInfo(InformInvestigationEndFormDto informInvestigationEndFormDto, String handleType, String casePartiesReasonType) {
        String caseId = informInvestigationEndFormDto.getCaseId();
        CaseMainDetailInfo updateCaseMainDetailInfo = new CaseMainDetailInfo();
        CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
        updateCaseMainDetailInfo.setCaseId(caseId);
        caseMainDetailAuxiliaryInfo.setCaseId(caseId);
        updateCaseMainDetailInfo.setHandleConclusion(informInvestigationEndFormDto.getHandleConclusion());
        //应急案由处理
        if (!ObjectUtils.isEmpty(informInvestigationEndFormDto.getCaseEmergencyReasonList())) {
            updateCaseMainDetailInfo.setCaseEmergencyReasonContent(JSON.toJSONString(informInvestigationEndFormDto.getCaseEmergencyReasonList()));
        }
        //如果为涉刑移送 集体议案赋值为空
        if (Constant.STRING_1.equals(informInvestigationEndFormDto.getHandleConclusion())) {
            informInvestigationEndFormDto.setIsNeedCollectiveDiscuss("");
        }
        //如果为行政处理 集体议案赋值为空 赋值处理内容
        if (Constant.STRING_1.equals(informInvestigationEndFormDto.getHandleConclusion())) {
            informInvestigationEndFormDto.setIsNeedCollectiveDiscuss("");
        }
        if (Constant.STRING_1.equals(handleType) || Constant.STRING_0.equals(handleType)) {
            caseMainDetailAuxiliaryInfo.setDisposeContext(informInvestigationEndFormDto.getDisposeContext());
            //合并处罚
            updateCaseMainDetailInfo.setPunishKinds(informInvestigationEndFormDto.getPunishKinds());
            updateCaseMainDetailInfo.setDiscretionInterval(informInvestigationEndFormDto.getDiscretionInterval());
            updateCaseMainDetailInfo.setDraftPunishMoney(informInvestigationEndFormDto.getDraftPunishMoney());
            //获取doc案由
            updateCaseMainDetailInfo.setIllegalSituation(informInvestigationEndFormDto.getIllegalSituation());
            updateCaseMainDetailInfo.setConfiscateIllegalMoney(informInvestigationEndFormDto.getConfiscateIllegalMoney());
            updateCaseMainDetailInfo.setIllegalLevel(informInvestigationEndFormDto.getIllegalLevel());
            updateCaseMainDetailInfo.setPunishContent(informInvestigationEndFormDto.getPunishContent());
            if (Constant.STRING_2.equals(informInvestigationEndFormDto.getInvestConclusion())) {
                updateCaseMainDetailInfo.setPunishContent("不予处罚");
            }
            updateCaseMainDetailInfo.setConfiscateIllegalProperty(informInvestigationEndFormDto.getConfiscateIllegalProperty());
            updateCaseMainDetailInfo.setConfiscateIllegalPropertyValue(informInvestigationEndFormDto.getConfiscateIllegalPropertyValue());
            updateCaseMainDetailInfo.setInvestConclusion(informInvestigationEndFormDto.getInvestConclusion());
            updateCaseMainDetailInfo.setNotGivePunishReason(informInvestigationEndFormDto.getNotGivePunishReason());
            updateCaseMainDetailInfo.setNotGivePunishDetail(informInvestigationEndFormDto.getNotGivePunishDetail());


            //合并处罚
            caseMainDetailAuxiliaryInfo.setPunishKinds(informInvestigationEndFormDto.getPunishKinds());
            caseMainDetailAuxiliaryInfo.setDiscretionInterval(informInvestigationEndFormDto.getDiscretionInterval());
            caseMainDetailAuxiliaryInfo.setDraftPunishMoney(informInvestigationEndFormDto.getDraftPunishMoney());
            //获取doc案由
            caseMainDetailAuxiliaryInfo.setIllegalSituation(informInvestigationEndFormDto.getIllegalSituation());
            caseMainDetailAuxiliaryInfo.setConfiscateIllegalMoney(informInvestigationEndFormDto.getConfiscateIllegalMoney());
            caseMainDetailAuxiliaryInfo.setIllegalLevel(informInvestigationEndFormDto.getIllegalLevel());
            caseMainDetailAuxiliaryInfo.setPunishContent(informInvestigationEndFormDto.getPunishContent());
            if (Constant.STRING_2.equals(informInvestigationEndFormDto.getInvestConclusion())) {
                caseMainDetailAuxiliaryInfo.setPunishContent("不予处罚");
            }
            caseMainDetailAuxiliaryInfo.setConfiscateIllegalProperty(informInvestigationEndFormDto.getConfiscateIllegalProperty());
            caseMainDetailAuxiliaryInfo.setConfiscateIllegalPropertyValue(informInvestigationEndFormDto.getConfiscateIllegalPropertyValue());
            caseMainDetailAuxiliaryInfo.setInvestConclusion(informInvestigationEndFormDto.getInvestConclusion());
            caseMainDetailAuxiliaryInfo.setNotGivePunishReason(informInvestigationEndFormDto.getNotGivePunishReason());
            caseMainDetailAuxiliaryInfo.setNotGivePunishDetail(informInvestigationEndFormDto.getNotGivePunishDetail());

        }
        String isNeedCollectiveDiscuss = informInvestigationEndFormDto.getIsNeedCollectiveDiscuss();
        if (StringUtils.isBlank(isNeedCollectiveDiscuss)) {
            isNeedCollectiveDiscuss = "0";
        }
        updateCaseMainDetailInfo.setIsNeedCollectiveDiscuss(isNeedCollectiveDiscuss);
        updateCaseMainDetailInfo.setIsImportantCase(informInvestigationEndFormDto.getIsImportantCase());
        updateCaseMainDetailInfo.setInvestigationEndDate(DateUtils.formatDate(new Date(), "yyyy年MM月dd日"));
        Example casePartiesRecordExample = new Example(CasePartiesRecord.class);
        casePartiesRecordExample.createCriteria().andEqualTo("caseId", informInvestigationEndFormDto.getCaseId()).andEqualTo("status", Constant.STRING_1);
        casePartiesRecordExample.setOrderByClause(" party_type desc,create_time asc ");
        List<CasePartiesRecordVo> casePartiesRecords = casePartiesRecordService.getCasePartiesInfo(caseId);
        String dsrName = "";
        String caseReason = "";
        for (CasePartiesRecordVo casePartiesRecord : casePartiesRecords) {
            if (StringUtils.isBlank(dsrName)) {
                dsrName = casePartiesRecord.getPartyName();
            } else {
                dsrName = dsrName + "、" + casePartiesRecord.getPartyName();
            }
        }
        Example reasonExample = new Example(CaseReasonMainRecord.class);
        reasonExample.createCriteria().andEqualTo("caseId", informInvestigationEndFormDto.getCaseId()).andEqualTo("status", "1");
        List<CaseReasonMainRecord> caseReasonMainRecords = caseReasonMainRecordMapper.selectByExample(reasonExample);
        for (CaseReasonMainRecord caseReasonMainRecord : caseReasonMainRecords) {
            if (StringUtils.isBlank(caseReason)) {
                caseReason = BaseUtil.handleCaseReason(caseReasonMainRecord.getCaseReasonName());
            } else {
                caseReason = caseReason + "、" + BaseUtil.handleCaseReason(caseReasonMainRecord.getCaseReasonName());
            }
        }
        updateCaseMainDetailInfo.setCaseReason(caseReason);
        updateCaseMainDetailInfo.setDocCaseReason(dsrName + "涉嫌" + caseReason);
        /*String caseName="";
        if(Constant.STRING_1.equals(casePartiesReasonType)){
            caseName=casePartiesRecords.get(0).getPartyName()+BaseUtil.handleCaseReason(caseReasonMainRecords.get(0).getCaseReasonName());
        }else if(Constant.STRING_2.equals(casePartiesReasonType)){
            caseName=casePartiesRecords.get(0).getPartyName()+BaseUtil.handleCaseReason(caseReasonMainRecords.get(0).getCaseReasonName())+"等"+caseReasonMainRecords.size()+"项违法行为案";
        }else if(Constant.STRING_3.equals(casePartiesReasonType)){
            caseName=casePartiesRecords.get(0).getPartyName()+"等"+casePartiesRecords.size()+"人"+BaseUtil.handleCaseReason(caseReasonMainRecords.get(0).getCaseReasonName());
        }*/
        updateCaseMainDetailInfo.setCaseName(informInvestigationEndFormDto.getCaseName());
        if (!ObjectUtils.isEmpty(informInvestigationEndFormDto.getCaseProceedTime())) {
            Example example = new Example(CaseMainDetailInfo.class);
            example.createCriteria().andEqualTo("caseId", caseId);
            List<CaseMainDetailInfo> caseMainDetailInfos = caseMainDetailInfoMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(caseMainDetailInfos)) {
                if (!informInvestigationEndFormDto.getCaseProceedTime().isBefore(caseMainDetailInfos.get(0).getCaseHappenTime().plusDays(1))) {
                    throw new BusinessException("案发时间不能晚于案件发现时间");
                }
            }
            updateCaseMainDetailInfo.setCaseProceedTime(informInvestigationEndFormDto.getCaseProceedTime());
            updateCaseMainDetailInfo.setCaseInvestigateTime(informInvestigationEndFormDto.getCaseInvestigateTime());
        }
        //添加办案结论(生态环境)
        if (StrUtil.isNotEmpty(informInvestigationEndFormDto.getDiscussConclusion())) {
            updateCaseMainDetailInfo.setDiscussConclusion(informInvestigationEndFormDto.getDiscussConclusion());
        }
        caseMainDetailInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailInfo);
        if ((Constant.STRING_1.equals(handleType) || Constant.STRING_0.equals(handleType))
                && !PartiesReasonTypeEnum.MULTIPLE_REASONS.getCode().equals(casePartiesReasonType)) {
            //多案由不更新
            try {
                //非分别处罚更新
                caseMainDetailAuxiliaryInfo.setCaseId(caseId);
                caseMainDetailAuxiliaryInfoService.editSpecialParamSingle(caseMainDetailAuxiliaryInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 多案由单当事人保存
     *
     * @param informInvestigationEndFormDto
     * @return
     * @author liyafeng
     * @date 2022/5/18
     */
    private void saveMultipleCaseReason(InformInvestigationEndFormDto informInvestigationEndFormDto) {
        //1.更新案件主表 处置方式
        String handleType = Constant.STRING_1;
        editCaseMainInfo(informInvestigationEndFormDto, handleType);
        //删除附件
        caseAppendixRecordService.removeCaseAppendixRecordByCaseIdAndCatalogCode(informInvestigationEndFormDto.getCaseId(), informInvestigationEndFormDto.getDocCatalogCode());
        //2.更新案由表 并 插入案件详情补充表
        //无效案由原有数据
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("caseId", informInvestigationEndFormDto.getCaseId());
        caseReasonMainRecordMapper.updateCaseReasonMainRecordStatus(paramMap);
        //新增案由表数据
        List<InvestEndMultiple> investEndMultipleList = informInvestigationEndFormDto.getInvestEndMultipleList();
        for (InvestEndMultiple investEndMultiple : investEndMultipleList) {
            String caseReasonRecordId = StringUtils.uuid();
            CaseReasonMainRecord caseReasonMainRecord = new CaseReasonMainRecord();
            BeanUtils.copyProperties(investEndMultiple, caseReasonMainRecord);
            caseReasonMainRecord.setCaseId(informInvestigationEndFormDto.getCaseId());
            caseReasonMainRecord.setId(caseReasonRecordId);
//            caseReasonMainRecord.setCaseReasonCode(investEndMultiple.getCaseReasonCode());
//            caseReasonMainRecord.setCaseReasonName(investEndMultiple.getCaseReason());
//            caseReasonMainRecord.setCaseReasonNodeid(investEndMultiple.getCaseReasonNodeid());
//            caseReasonMainRecord.setItemVersionCode(investEndMultiple.getItemVersionCode());
//            caseReasonMainRecord.setTerritoryCode(investEndMultiple.getTerritoryCode());
            caseReasonMainRecord.setCaseReasonName(investEndMultiple.getCaseReason());
            caseReasonMainRecord.setIllegalBasis(investEndMultiple.getViolateRuleInfos().get(0).getIllegalBasis());
            caseReasonMainRecord.setIllegalDetail(investEndMultiple.getViolateRuleInfos().get(0).getIllegalDetail());
            caseReasonMainRecord.setPunishBasis(investEndMultiple.getPunishRuleInfos().get(0).getPunishBasis());
            caseReasonMainRecord.setPunishDetail(investEndMultiple.getPunishRuleInfos().get(0).getPunishDetail());
            caseReasonMainRecord.setCreateTime(LocalDateTime.now());
//            caseReasonMainRecord.setClaimId(investEndMultiple.getClaimId());
            caseReasonMainRecord.setStatus("1");
            caseReasonMainRecord.setCaseReasonNameSimple(BaseUtil.handleCaseReason(investEndMultiple.getCaseReason()));
            caseReasonMainRecord.setIllegalBasisFormat(BaseUtil.removeHtml(investEndMultiple.getViolateRuleInfos().get(0).getIllegalBasis()));
            caseReasonMainRecord.setIllegalDetailFormat(BaseUtil.removeHtml(investEndMultiple.getViolateRuleInfos().get(0).getIllegalDetail()));
            caseReasonMainRecord.setPunishBasisFormat(BaseUtil.removeHtml(investEndMultiple.getPunishRuleInfos().get(0).getPunishBasis()));
            caseReasonMainRecord.setPunishDetailFormat(BaseUtil.removeHtml(investEndMultiple.getPunishRuleInfos().get(0).getPunishDetail()));
            caseReasonMainRecordMapper.insert(caseReasonMainRecord);
            //根据id更新案件详情补充表
            CaseMainDetailAuxiliaryInfo updateCaseMainDetailAuxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
            BeanUtils.copyProperties(investEndMultiple, updateCaseMainDetailAuxiliaryInfo);
            updateCaseMainDetailAuxiliaryInfo.setId(investEndMultiple.getId());
            updateCaseMainDetailAuxiliaryInfo.setCaseReasonId(caseReasonRecordId);
            updateCaseMainDetailAuxiliaryInfo.setCaseReasonName(investEndMultiple.getCaseReason());
            updateCaseMainDetailAuxiliaryInfo.setDisposeContext(investEndMultiple.getDisposeContext());
            caseMainDetailAuxiliaryInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailAuxiliaryInfo);
            //4.附件保存
            saveAppendixDto(informInvestigationEndFormDto.getCaseId(), informInvestigationEndFormDto.getDocCatalogCode(), investEndMultiple.getId(), investEndMultiple.getAppendixList());
        }
        //3.更新案件详情表
        editCaseMainDetailInfo(informInvestigationEndFormDto, handleType, Constant.STRING_2);
        //涉刑移送附件保存处理
        if (Constant.STRING_1.equals(informInvestigationEndFormDto.getHandleConclusion())) {
            saveCaseAppendixRecord(informInvestigationEndFormDto);
        }
    }

    /**
     * 附件保存
     *
     * @param caseId
     * @param docCatalogCode
     * @param id
     * @param appendixList
     * @return
     * @author liyafeng
     * @date 2022/5/19
     */
    private void saveAppendixDto(String caseId, String docCatalogCode, String id, List<AppendixDto> appendixList) {
        CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = caseMainDetailAuxiliaryInfoMapper.selectByPrimaryKey(id);
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        List<AppendixDto> list = appendixList;
        if (null != list && list.size() > 0) {
            for (AppendixDto appendixDto : list) {
                CaseAppendixRecord record = new CaseAppendixRecord();
                record.setCaseId(caseId);
                record.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
                record.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
                record.setAppendixUrl(appendixDto.getAppendixUrl());
                record.setAppendixTypeId(appendixDto.getAppendixTypeId());
                record.setAppendixName(appendixDto.getAppendixName());
                record.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
                record.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
                record.setDocumentCatalogCode(docCatalogCode);
                record.setPartyId(caseMainDetailAuxiliaryInfo.getPartyId());
                record.setCaseReasonId(caseMainDetailAuxiliaryInfo.getCaseReasonId());
                caseAppendixRecordService.saveCaseAppendixRecord(record);
            }
        }

    }

    /**
     * 单案由单当事人保存
     *
     * @param informInvestigationEndFormDto
     * @return
     * @author liyafeng
     * @date 2022/5/18
     */
    private void saveSingleCaseReasonAndParty(InformInvestigationEndFormDto informInvestigationEndFormDto) {
        //1.更新案件主表 处置方式
        String handleType = Constant.STRING_0;
        editCaseMainInfo(informInvestigationEndFormDto, handleType);
        //2.更新案由表
        //无效原有数据
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("caseId", informInvestigationEndFormDto.getCaseId());
        caseReasonMainRecordMapper.updateCaseReasonMainRecordStatus(paramMap);
        //插入有效数据
        saveCaseResonRecordByDto(informInvestigationEndFormDto);
        //3.更新案件详情表
        editCaseMainDetailInfo(informInvestigationEndFormDto, handleType, Constant.STRING_1);
        //4.附件保存
        saveCaseAppendixRecord(informInvestigationEndFormDto);
    }

    /**
     * 附件处理
     *
     * @param informInvestigationEndFormDto
     */
    private void saveCaseAppendixRecord(InformInvestigationEndFormDto informInvestigationEndFormDto) {
        caseAppendixRecordService.removeCaseAppendixRecordByCaseIdAndCatalogCode(informInvestigationEndFormDto.getCaseId(), informInvestigationEndFormDto.getDocCatalogCode());
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(informInvestigationEndFormDto.getCaseId());
        List<AppendixDto> list = informInvestigationEndFormDto.getAppendixList();
        for (int i = 0; i < list.size(); i++) {
            CaseAppendixRecord record = new CaseAppendixRecord();
            record.setCaseId(informInvestigationEndFormDto.getCaseId());
            record.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
            record.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
            record.setAppendixUrl(informInvestigationEndFormDto.getAppendixList().get(i).getAppendixUrl());
            record.setAppendixTypeId(informInvestigationEndFormDto.getAppendixList().get(i).getAppendixTypeId());
            record.setAppendixName(informInvestigationEndFormDto.getAppendixList().get(i).getAppendixName());
            record.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
            record.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
            record.setDocumentCatalogCode(informInvestigationEndFormDto.getDocCatalogCode());
            caseAppendixRecordService.saveCaseAppendixRecord(record);
        }
    }

    /**
     * 保存案由数据
     *
     * @param informInvestigationEndFormDto
     * @return
     * @author liyafeng
     * @date 2022/5/19
     */
    private String saveCaseResonRecordByDto(InformInvestigationEndFormDto informInvestigationEndFormDto) {
        String caseReasonRecordId = StringUtils.uuid();
        List<ViolateRuleInfo> violateRuleInfos = informInvestigationEndFormDto.getViolateRuleInfos();
        List<PunishRuleInfo> punishRuleInfos = informInvestigationEndFormDto.getPunishRuleInfos();
        CaseReasonMainRecord caseReasonMainRecord = new CaseReasonMainRecord();
        caseReasonMainRecord.setCaseId(informInvestigationEndFormDto.getCaseId());
        caseReasonMainRecord.setId(caseReasonRecordId);
        caseReasonMainRecord.setCaseReasonCode(informInvestigationEndFormDto.getCaseReasonCode());
        caseReasonMainRecord.setCaseReasonName(informInvestigationEndFormDto.getCaseReason());
        caseReasonMainRecord.setCaseReasonNodeid(informInvestigationEndFormDto.getCaseReasonNodeid());
        caseReasonMainRecord.setItemVersionCode(informInvestigationEndFormDto.getItemVersionCode());
        caseReasonMainRecord.setTerritoryCode(informInvestigationEndFormDto.getTerritoryCode());
        caseReasonMainRecord.setIllegalBasis(violateRuleInfos.get(0).getIllegalBasis());
        caseReasonMainRecord.setIllegalDetail(violateRuleInfos.get(0).getIllegalDetail());
        caseReasonMainRecord.setPunishBasis(punishRuleInfos.get(0).getPunishBasis());
        caseReasonMainRecord.setPunishDetail(punishRuleInfos.get(0).getPunishDetail());
        caseReasonMainRecord.setCreateTime(LocalDateTime.now());
        caseReasonMainRecord.setClaimId(informInvestigationEndFormDto.getClaimId());
        caseReasonMainRecord.setStatus("1");
        caseReasonMainRecord.setCaseReasonNameSimple(BaseUtil.handleCaseReason(informInvestigationEndFormDto.getCaseReason()));
        caseReasonMainRecord.setIllegalBasisFormat(BaseUtil.removeHtml(violateRuleInfos.get(0).getIllegalBasis()));
        caseReasonMainRecord.setIllegalDetailFormat(BaseUtil.removeHtml(violateRuleInfos.get(0).getIllegalDetail()));
        caseReasonMainRecord.setPunishBasisFormat(BaseUtil.removeHtml(punishRuleInfos.get(0).getPunishBasis()));
        caseReasonMainRecord.setPunishDetailFormat(BaseUtil.removeHtml(punishRuleInfos.get(0).getPunishDetail()));
        caseReasonMainRecordMapper.insert(caseReasonMainRecord);
        return caseReasonRecordId;
    }

    /**
     * 更新案件主表
     *
     * @param informInvestigationEndFormDto
     * @param handleType
     * @return
     * @author liyafeng
     * @date 2022/5/19
     */
    private void editCaseMainInfo(InformInvestigationEndFormDto informInvestigationEndFormDto, String handleType) {
        CaseMainInfo updateCaseMainInfo = new CaseMainInfo();
        updateCaseMainInfo.setId(informInvestigationEndFormDto.getCaseId());
        //单案由当当事人 默认为常规处罚
        updateCaseMainInfo.setHandleType(handleType);
        updateCaseMainInfo.setCaseName(informInvestigationEndFormDto.getCaseName());
        caseMainInfoMapper.updateByPrimaryKeySelective(updateCaseMainInfo);
    }

    /**
     * 描述： 获取案件是否需要集体议案
     *
     * @return {@link Result< String>}
     * @author: zhengqiang
     * @date: 2022/7/11
     * @param: formDto
     **/
    @Override
    public Result<String> getIsNeedCollectiveDiscussResult(IsNeedCollectiveDiscussCheckDto checkDto) {
        //默认不需要集体议案
        String isNeedCollectiveDiscuss = YesOrNoEnum.NO.getCode();
        //案件id
        String caseId = checkDto.getCaseId();
        //判定依据类型:集体议案
        String decideBasisType = DecideBasisTypeEnum.COLLECTIVE_DISCUSS.getCode();
        //案由、当事人类型
        String casePartiesReasonType = checkDto.getCasePartiesReasonType();
        //处罚类型
        String handleType = checkDto.getHandleType();
        //多当事人分别处罚
        if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)
                && HandleTypeEnum.PART_PUNISH.getCode().equals(handleType)) {
            List<InvestEndMultipleCheckDto> investEndMultipleList = checkDto.getInvestEndMultipleList();
            if (ObjectUtils.isEmpty(investEndMultipleList)) {
                return Result.success("success", YesOrNoEnum.NO.getCode());
            }
            for (InvestEndMultipleCheckDto investEndMultiple : investEndMultipleList) {
                if (ObjectUtils.isEmpty(investEndMultiple.getPunishKinds())) {
                    return Result.success("success", YesOrNoEnum.NO.getCode());
                }
                //处罚金额
                String draftPunishMoney = investEndMultiple.getDraftPunishMoney();
                //没收违法所得
                String confiscateIllegalMoney = investEndMultiple.getConfiscateIllegalMoney();
                //当前案件处罚种类
                List<String> punishKindsList = Arrays.asList(investEndMultiple.getPunishKinds().split(","));
                //查询当事人信息
                Example example = new Example(CasePartiesRecord.class);
                example.createCriteria().andEqualTo("partyId", investEndMultiple.getPartyId()).andEqualTo("status", Constant.STRING_1);
                List<CasePartiesRecord> casePartiesRecords = casePartiesRecordMapper.selectByExample(example);
                if (ObjectUtils.isEmpty(casePartiesRecords)) {
                    return Result.success("success", YesOrNoEnum.NO.getCode());
                }

                String partyType = casePartiesRecords.get(0).getPartyType();
                String result = configOrgDecideBasisInfoService.checkIsNeedByConfigOrgDecideBasis(caseId, decideBasisType, punishKindsList, draftPunishMoney, confiscateIllegalMoney, partyType, "");
                if (YesOrNoEnum.NO.getCode().equals(result)) {
                    return Result.success("success", YesOrNoEnum.NO.getCode());
                }
                isNeedCollectiveDiscuss = YesOrNoEnum.YES.getCode();
                break;

            }

        } else {
            //处罚种类为空
            if (ObjectUtils.isEmpty(checkDto.getPunishKinds())) {
                return Result.success("success", YesOrNoEnum.NO.getCode());
            }

            //处罚金额
            String draftPunishMoney = checkDto.getDraftPunishMoney();
            //没收违法所得
            String confiscateIllegalMoney = checkDto.getConfiscateIllegalMoney();
            //查询当事人信息
            List<CasePartiesRecordVo> casePartiesRecords = casePartiesRecordService.getCasePartiesInfo(checkDto.getCaseId());
            String partyType = casePartiesRecords.get(0).getPartyType();
            if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)) {
                //默认为个人
                partyType = PartyTypeEnum.PERSON.getCode();
                //多当事人合并处罚,当事人包含单位则按单位额度
                boolean b = casePartiesRecords.stream().anyMatch(casePartiesRecordVo -> PartyTypeEnum.LEGAL.getCode().equals(casePartiesRecordVo.getPartyType()));
                if (b) {
                    partyType = PartyTypeEnum.LEGAL.getCode();
                }
            }
            //当前案件处罚种类
            List<String> punishKindsList = Arrays.asList(checkDto.getPunishKinds().split(","));

            isNeedCollectiveDiscuss = configOrgDecideBasisInfoService.checkIsNeedByConfigOrgDecideBasis(caseId, decideBasisType, punishKindsList, draftPunishMoney, confiscateIllegalMoney, partyType, "");
        }
        return Result.success("success", isNeedCollectiveDiscuss);
    }

    /**
     * 简案快办补充信息保存
     *
     * @param fastCaseAddInfoDto
     * @return {@link int}
     * @author liyafeng
     * @date 2023/4/20
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public int saveFastCaseAddInfo(FastCaseAddInfoDto fastCaseAddInfoDto) {
        //删除暂存信息
        Example example = new Example(CaseTemporaryRecord.class);
        example.createCriteria().andEqualTo("caseId", fastCaseAddInfoDto.getCaseId()).andEqualTo("documentCatalogCode", Constant.STRING_TEMP_FAST_CASE_ADD_INFO);
        caseTemporaryRecordMapper.deleteByExample(example);
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(fastCaseAddInfoDto.getCaseId());
        CaseMainDetailInfo updateCaseMainDetailInfo = new CaseMainDetailInfo();
        BeanUtils.copyProperties(fastCaseAddInfoDto, updateCaseMainDetailInfo);
        updateCaseMainDetailInfo.setIsHearing(Constant.STRING_0);
        updateCaseMainDetailInfo.setIsNeedCollectiveDiscuss(Constant.STRING_0);
        updateCaseMainDetailInfo.setCaseId(fastCaseAddInfoDto.getCaseId());
        updateCaseMainDetailInfo.setPunishBeforeInformPeriod(Integer.valueOf(fastCaseAddInfoDto.getStatementPleadTerm()));
        int num = caseMainDetailInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailInfo);
        //更新主表名称
        CaseMainInfo updateCaseMainInfo = new CaseMainInfo();
        updateCaseMainInfo.setId(caseMainInfo.getId());
        updateCaseMainInfo.setCaseName(fastCaseAddInfoDto.getCaseName());
        caseMainInfoMapper.updateByPrimaryKeySelective(updateCaseMainInfo);
        List<AppendixDto> list = fastCaseAddInfoDto.getAppendixList();
        if (!ObjectUtils.isEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                CaseAppendixRecord record = new CaseAppendixRecord();
                record.setCaseId(fastCaseAddInfoDto.getCaseId());
                record.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
                record.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
                record.setAppendixUrl(fastCaseAddInfoDto.getAppendixList().get(i).getAppendixUrl());
                record.setAppendixTypeId(fastCaseAddInfoDto.getAppendixList().get(i).getAppendixTypeId());
                record.setAppendixName(fastCaseAddInfoDto.getAppendixList().get(i).getAppendixName());
                record.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
                record.setCaseLinkName(caseMainInfo.getCaseCurrentLinkName());
                //record.setDocumentCatalogCode(fastCaseAddInfoDto.getDocCatalogCode());
                caseAppendixRecordService.saveCaseAppendixRecord(record);
            }
        }
        //生成4分文书
        fastCaseDocumentRecordService.saveFastCaseRegisterDocument(fastCaseAddInfoDto.getCaseId(), fastCaseAddInfoDto);
        return num;
    }

    /**
     * 简案快办补充信息暂存
     *
     * @param fastCaseAddInfoDto
     * @return {@link int}
     * @author liyafeng
     * @date 2023/5/6
     */
    @Override
    public int saveFastCaseAddInfoTemporary(FastCaseAddInfoDto fastCaseAddInfoDto) {
        UserDTO userDTO = UserUtil.getUserInfo();
        //如果存在则更新
        Example example = new Example(CaseTemporaryRecord.class);
        example.createCriteria().andEqualTo("caseId", fastCaseAddInfoDto.getCaseId()).andEqualTo("documentCatalogCode", Constant.STRING_TEMP_FAST_CASE_ADD_INFO);
        List<CaseTemporaryRecord> caseTemporaryRecords = caseTemporaryRecordMapper.selectByExample(example);
        if (!ObjectUtils.isEmpty(caseTemporaryRecords)) {
            CaseTemporaryRecord caseTemporaryRecord = caseTemporaryRecords.get(0);
            CaseTemporaryRecord updaterecord = new CaseTemporaryRecord();
            updaterecord.setId(caseTemporaryRecord.getId());
            updaterecord.setAddUser(userDTO.getLoginName());
            updaterecord.setCreateTime(LocalDateTime.now());
            updaterecord.setContent(JSON.toJSONString(fastCaseAddInfoDto));
            return caseTemporaryRecordMapper.updateByPrimaryKeySelective(updaterecord);
        }
        CaseTemporaryRecord record = new CaseTemporaryRecord();
        record.setId(BaseUtil.createUid());
        record.setCaseId(fastCaseAddInfoDto.getCaseId());
        record.setContent(JSON.toJSONString(fastCaseAddInfoDto));
        record.setAddUser(userDTO.getLoginName());
        record.setCreateTime(LocalDateTime.now());
        record.setDocumentCatalogCode(Constant.STRING_TEMP_FAST_CASE_ADD_INFO);
        int num = caseTemporaryRecordMapper.insert(record);
        return num;
    }

    /**
     * 简案快办补充信息暂存获取
     *
     * @param dto
     * @return {@link FastCaseAddInfoDto}
     * @author liyafeng
     * @date 2023/5/6
     */
    @Override
    public FastCaseAddInfoDto getFastCaseAddInfoTemporary(FastCaseAddInfoTemporaryDto dto) {
        FastCaseAddInfoDto fastCaseAddInfoDto = new FastCaseAddInfoDto();
        Example example = new Example(CaseTemporaryRecord.class);
        example.createCriteria().andEqualTo("caseId", dto.getCaseId()).andEqualTo("documentCatalogCode", Constant.STRING_TEMP_FAST_CASE_ADD_INFO);
        List<CaseTemporaryRecord> caseTemporaryRecords = caseTemporaryRecordMapper.selectByExample(example);
        if (!ObjectUtils.isEmpty(caseTemporaryRecords)) {
            String fastCaseAddInfoDtoStr = caseTemporaryRecords.get(Constant.INTEGER_0).getContent();
            fastCaseAddInfoDto = JSON.parseObject(fastCaseAddInfoDtoStr, FastCaseAddInfoDto.class);
        }
        return fastCaseAddInfoDto;
    }

    @Override
    public Result<String> saveInformInvestigationEndFormApp(AppInformInvestigationEndFormDto informInvestigationEndFormDto) {
        InformInvestigationEndFormDto investigationEndFormDto = convertToInformInvestigationEndFormDto(informInvestigationEndFormDto);
        // app 端不增加处罚告知的阶段. todo 更新下案子非听证类. case_main_detail 和 case_main_detail_axi
        return saveInformInvestigationEndForm(investigationEndFormDto);
    }


    public static InformInvestigationEndFormDto convertToInformInvestigationEndFormDto(AppInformInvestigationEndFormDto item) {
        if (item == null) {
            return null;
        }
        InformInvestigationEndFormDto result = new InformInvestigationEndFormDto();
        result.setCasePartiesReasonType(item.getCasePartiesReasonType());
        result.setDocCatalogCode(item.getDocCatalogCode());
        result.setCaseId(item.getCaseId());
        result.setInvestEndMultipleList(item.getInvestEndMultipleList());
        result.setCaseReason(item.getCaseReason());
        result.setCaseReasonCode(item.getCaseReasonCode());
//        result.setCaseName();
        result.setViolateRuleInfos(item.getViolateRuleInfos());
        result.setPunishRuleInfos(item.getPunishRuleInfos());
        result.setIllegalSituation(item.getIllegalSituation());
        result.setPunishKinds(item.getPunishKinds());
        result.setDiscretionInterval(item.getDiscretionInterval());
        result.setDraftPunishMoney(item.getDraftPunishMoney());
        result.setPunishContent(item.getPunishContent());
        result.setIsImportantCase(item.getIsImportantCase());
        result.setIsNeedCollectiveDiscuss(item.getIsNeedCollectiveDiscuss());
        result.setIllegalLevel(item.getIllegalLevel());
        result.setCaseReasonNodeid(item.getCaseReasonNodeid());
        result.setItemVersionCode(item.getItemVersionCode());
        result.setTerritoryCode(item.getTerritoryCode());
        result.setConfiscateIllegalMoney(item.getConfiscateIllegalMoney());
        result.setClaimId(item.getClaimId());
        result.setConfiscateIllegalProperty(item.getConfiscateIllegalProperty());
        result.setConfiscateIllegalPropertyValue(item.getConfiscateIllegalPropertyValue());
        result.setInvestConclusion(item.getInvestConclusion());
        result.setNotGivePunishReason(item.getNotGivePunishReason());
        result.setNotGivePunishDetail(item.getNotGivePunishDetail());
        result.setAppendixList(item.getAppendixList());
        result.setHandleType(item.getHandleType());
        result.setCaseProceedTime(item.getCaseProceedTime());
        result.setHandleConclusion(item.getHandleConclusion());
        result.setDisposeContext(item.getDisposeContext());
        result.setPersonReasonIds(item.getPersonReasonIds());
        result.setPersonReasonNames(item.getPersonReasonNames());
        result.setCaseEmergencyReasonList(item.getCaseEmergencyReasonList());
        result.setCaseInvestigateTime(item.getCaseInvestigateTime());
        result.setDiscussConclusion(item.getDiscussConclusion());
        return result;
    }

    /**
     * 描述： 【V1.4.1】描述： 保存案由调整记录
     *
     * @return
     * @author: zhengqiang
     * @date: 2022/8/23
     **/
    private boolean saveAdjustInfoWithCaseReason(InformInvestigationEndFormDto informInvestigationEndFormDto) {
        boolean isChange = false;
        String caseId = informInvestigationEndFormDto.getCaseId();
        //校验案由是否有调整
        String caseReasonCodeBeforeAdjust = "";
        String caseReasonBeforeAdjust = "";
        List<String> oldCaseReasonList = new ArrayList();
        Example example = new Example(CaseReasonMainRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status", "1");
        List<CaseReasonMainRecord> caseReasonMainRecords = caseReasonMainRecordMapper.selectByExample(example);
        if (!ObjectUtils.isEmpty(caseReasonMainRecords)) {
            caseReasonBeforeAdjust = caseReasonMainRecords.stream().map(e -> e.getCaseReasonName()).collect(Collectors.joining(","));
            caseReasonCodeBeforeAdjust = caseReasonMainRecords.stream().map(e -> e.getCaseReasonCode()).collect(Collectors.joining(","));
            oldCaseReasonList = caseReasonMainRecords.stream().map(e -> e.getCaseReasonCode()).collect(Collectors.toList());
        }

        String caseReasonCodeAfterAdjust = "";
        String caseReasonAfterAdjust = "";
        List newCaseReasonList = new ArrayList();
        String casePartiesReasonType = informInvestigationEndFormDto.getCasePartiesReasonType();
        if (PartiesReasonTypeEnum.SINGLE_PARTY.getCode().equals(casePartiesReasonType)
                || PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)) {
            //单案由单当事人或单案由多当事人
            caseReasonAfterAdjust = informInvestigationEndFormDto.getCaseReason();
            caseReasonCodeAfterAdjust = informInvestigationEndFormDto.getCaseReasonCode();
            newCaseReasonList.add(informInvestigationEndFormDto.getCaseReasonCode());
        } else if (PartiesReasonTypeEnum.MULTIPLE_REASONS.getCode().equals(casePartiesReasonType)) {
            //多案由单当事人
            List<InvestEndMultiple> investEndMultipleList = informInvestigationEndFormDto.getInvestEndMultipleList();
            caseReasonAfterAdjust = investEndMultipleList.stream().map(e -> e.getCaseReason()).collect(Collectors.joining(","));
            caseReasonCodeAfterAdjust = investEndMultipleList.stream().map(e -> e.getCaseReasonCode()).collect(Collectors.joining(","));
            newCaseReasonList = investEndMultipleList.stream().map(e -> e.getCaseReasonCode()).collect(Collectors.toList());
        }

        if (!oldCaseReasonList.containsAll(newCaseReasonList) || !newCaseReasonList.containsAll(oldCaseReasonList)) {
            isChange = true;
        }

        if (isChange) {
            CaseReasonInfoAdjustDto adjustDto = new CaseReasonInfoAdjustDto();
            adjustDto.setCaseId(caseId);
            adjustDto.setCaseReasonCodeBeforeAdjust(caseReasonCodeBeforeAdjust);
            adjustDto.setCaseReasonBeforeAdjust(caseReasonBeforeAdjust);
            adjustDto.setCaseReasonCodeAfterAdjust(caseReasonCodeAfterAdjust);
            adjustDto.setCaseReasonAfterAdjust(caseReasonAfterAdjust);
            caseInfoAdjustRecordService.saveAdjustInfoWithCaseReason(adjustDto);
        }
        return isChange;
    }

    /**
     * 描述校验案由违则罚则
     *
     * @author shishengyao
     * @date 2022/10/19
     */
    private void checkCaseReasonViolateRuleAndPunishRule(InformInvestigationEndFormDto informInvestigationEndFormDto) {
        String casePartiesReasonType = informInvestigationEndFormDto.getCasePartiesReasonType();
        List<ViolateRuleInfo> violateRuleInfos = new ArrayList<>();
        List<PunishRuleInfo> punishRuleInfos = new ArrayList<>();
        //单案由单当事人||单案由多当事人
        if (Constant.STRING_1.equals(casePartiesReasonType)
                || Constant.STRING_3.equals(casePartiesReasonType)) {
            violateRuleInfos = informInvestigationEndFormDto.getViolateRuleInfos();
            punishRuleInfos = informInvestigationEndFormDto.getPunishRuleInfos();
            ViolateRuleInfo violateRuleInfo = violateRuleInfos.get(0);
            PunishRuleInfo punishRuleInfo = punishRuleInfos.get(0);
            if (ObjectUtils.isEmpty(violateRuleInfo.getIllegalBasis())) {
                throw new BusinessException("违则不能为空,请补充违则");
            }
            if (ObjectUtils.isEmpty(punishRuleInfo.getPunishBasis())) {
                throw new BusinessException("罚则不能为空，请补充罚则");
            }
        } else if (Constant.STRING_2.equals(casePartiesReasonType)) {
            //多案由单当事人
            List<InvestEndMultiple> investEndMultipleList = informInvestigationEndFormDto.getInvestEndMultipleList();
            for (InvestEndMultiple investEndMultiple : investEndMultipleList) {
                violateRuleInfos = investEndMultiple.getViolateRuleInfos();
                punishRuleInfos = investEndMultiple.getPunishRuleInfos();
                ViolateRuleInfo violateRuleInfo = violateRuleInfos.get(0);
                PunishRuleInfo punishRuleInfo = punishRuleInfos.get(0);
                if (ObjectUtils.isEmpty(violateRuleInfo.getIllegalBasis())) {
                    throw new BusinessException(investEndMultiple.getCaseReason() + "的违则不能为空,请补充违则");
                }
                if (ObjectUtils.isEmpty(punishRuleInfo.getPunishBasis())) {
                    throw new BusinessException(investEndMultiple.getCaseReason() + "的罚则不能为空，请补充罚则");
                }
            }
        }
    }

    /**
     * 调查终结相关文书处理
     *
     * @param informInvestigationEndFormDto
     */
    private void dealInvestigationDocument(InformInvestigationEndFormDto informInvestigationEndFormDto) {
        String caseId = informInvestigationEndFormDto.getCaseId();
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(caseId);
        if (!ObjectUtils.isEmpty(caseMainDetailInfo.getHandleConclusion())
                && !informInvestigationEndFormDto.getHandleConclusion().equals(caseMainDetailInfo.getHandleConclusion())) {
            //处理结论handleConclusion发生变化时删除之前保存的文书--行政处罚与涉刑移送的文书不一致
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(informInvestigationEndFormDto.getDocCatalogCode());
            String relationDocumentCatalogCode = configBusiParamDocumentInfo.getRelationDocumentCatalogCode();
            if (!ObjectUtils.isEmpty(relationDocumentCatalogCode)) {
                relationDocumentCatalogCode = informInvestigationEndFormDto.getDocCatalogCode() + "," + relationDocumentCatalogCode;
                String[] catalogCodeArr = relationDocumentCatalogCode.split(",");
                for (String catalogCode : catalogCodeArr) {
                    //删除文书记录
                    //查询文书记录数据
                    Example relateExample = new Example(CaseDocumentRecord.class);
                    relateExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", catalogCode)
                            //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                            .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
                    caseDocumentRecordMapper.deleteByExample(relateExample);
                }
            }
        }

    }

    /**
     * 判断案件是否是公安退回
     *
     * @param informInvestigationEndFormDto
     */
    private void checkCaseIsCriminalBack(InformInvestigationEndFormDto informInvestigationEndFormDto) {
        //涉刑退回的案件不允许再次发起涉刑移送
        if (Constant.STRING_1.equals(informInvestigationEndFormDto.getHandleConclusion())) {
            //涉刑案件
            //查询是否存在涉刑退回的记录
            int count = caseCriminalTransferFileMapper.selectCountCriminalBackRecord(informInvestigationEndFormDto.getCaseId());
            if (count > 0) {
                throw new BusinessException("涉刑退回的案件不允许再次发起涉刑移送");
            }
        }
    }
}
